/**
 * Copyright (c) 2007 The Apereo Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *             http://opensource.org/licenses/ecl2
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/*
 * This code is copied and slightly modified from the Apache Wicket project class
 * 	org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel
 * authored by jcompagner
 * 
 * That class is licensed under the following license:
 * 
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.sakaiproject.scorm.ui.player.components;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.head.OnDomReadyHeaderItem;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.request.cycle.RequestCycle;
import org.apache.wicket.request.mapper.parameter.PageParameters;

/**
 * A reusable Wicket Panel that defers the construction and rendering of an expensive child component
 * until after the page has been loaded in the browser. While the real content is being prepared
 * on the server, a small “loading” indicator is shown. Once the client-side DOM is ready, an Ajax
 * callback is triggered that asks the server to build the real component and replace the placeholder.
 *
 * Why/when to use:
 * - When the initial page contains heavy components (e.g., SCORM player launch area, large trees, or
 *   data-heavy panels) that would slow down the first render.
 * - When you want the page to become interactive quickly and progressively load complex sections.
 *
 * How it works (high level):
 * - On first render, this panel adds a lightweight placeholder (getLoadingComponent()) to markup id
 *   "content" and registers an Ajax behavior.
 * - When the DOM is ready, the behavior performs a callback. In respond(), the panel calls
 *   getLazyLoadComponent() to build the actual component and replaces the placeholder via Ajax.
 * - The implementation guards against duplicate/late callbacks: once the real content has been
 *   loaded, subsequent callbacks are ignored.
 *
 * Extending:
 * - Subclasses must implement getLazyLoadComponent(String markupId, AjaxRequestTarget target) and
 *   should create the real content bound to the provided markup id.
 * - Optionally override getLoadingComponent(String markupId, PageParameters params) to customize the
 *   loading indicator.
 *
 * Note:
 * This class is based on Apache Wicket's AjaxLazyLoadPanel with small adaptations for Sakai/SCORM
 * usage and more robust duplicate-callback handling.
 */
public abstract class LazyLoadPanel extends Panel
{
	private static final long serialVersionUID = 1L;

	private boolean loading = true;

	public LazyLoadPanel(String id, IModel model, PageParameters params)
	{
		super(id, model);
		setOutputMarkupId(true);
		setOutputMarkupPlaceholderTag(true);
		final Component loadingComponent = getLoadingComponent("content", params);
		add(loadingComponent.setRenderBodyOnly(true));

		add(new AbstractDefaultAjaxBehavior()
		{
			private static final long serialVersionUID = 1L;

			@Override
			protected void respond(AjaxRequestTarget target) {
				if (!loading) {
					return;
				}
				Component component = getLazyLoadComponent("content", target);
				LazyLoadPanel.this.replace(component.setRenderBodyOnly(true));
				loading = false;
				target.add(LazyLoadPanel.this);
			}

			@Override
			public void renderHead(Component component, IHeaderResponse response)
			{
				super.renderHead(component, response);
				response.render(OnDomReadyHeaderItem.forScript(getCallbackScript().toString()));
			}

			@Override
			public boolean isEnabled(Component component) {
				return true;
			}
		});
	}

	/**
	 * @param markupId The components markupid.
	 * @return The component that must be lazy created.
	 */
	public abstract Component getLazyLoadComponent(String markupId, AjaxRequestTarget target);

	/**
	 * @param markupId The components markupid.
	 * @return The component to show while the real component is being created.
	 */
	public Component getLoadingComponent(String markupId, PageParameters params)
	{
		return new Label(markupId, "<img src=\"" + RequestCycle.get().urlFor(AbstractDefaultAjaxBehavior.INDICATOR, params) + "\"/>").setEscapeModelStrings(false);
	}
}
